<?php
namespace App\Task;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Crontab\Annotation\Crontab;
use Hyperf\Di\Annotation\Inject;
use Hyperf\Context\ApplicationContext;
use Hyperf\DbConnection\Db;

#[Crontab(name: "updateProduct", rule: "*/5 * * * *", callback: "execute", memo: "每五分钟更新商品信息")]
class FooTask
{
    #[Inject]
    private StdoutLoggerInterface $logger;
	
	protected $redis;
	
	public function __construct()
	{
	    $container = ApplicationContext::getContainer();
	    $this->redis = $container->get(\Hyperf\Redis\Redis::class);
	}

    public function execute()
    {
		$productNormal = $this->redis->keys('product:normal:*');
		$productSpike = $this->redis->keys('product:spike:*');
		$productListAll = [];
		foreach ($productNormal as $key) {
		    $product = $this->redis->hgetall($key);
		    array_push($productListAll, $product);
		}
		foreach ($productSpike as $key) {
		    $product = $this->redis->hgetall($key);
		    array_push($productListAll, $product);
		}
		
		foreach($productListAll as $k => $v){
			$productData['name'] = $v['name'];
			$productData['price'] = $v['price'];
			$productData['num'] = $v['num'];
			$productData['is_sale'] = $v['is_sale'];
			$productData['start_time'] = $v['start_time'];
			$productData['end_time'] = $v['end_time'];
			$productData['max_buy'] = $v['max_buy'];
			Db::connection('default')->table('product')->where('id', $v['id'])->update($productData);
		}
    }
}
